<template>
  <div class="main">
    <breadcrumb/>
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="openAddCateDialog('add')">添加分类</el-button>
        </el-col>
      </el-row>
      <el-table :data="cateList" border stripe>
        <el-table-column label="#" type="expand">
          <template slot-scope="scope">
            <el-tree
              :data="scope.row.children"
              :props="defaultProps"
              :expand-on-click-node="false"
            >
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <span>{{ node.label }}</span>
                <span>
                  <el-button
                    type="text"
                    size="mini"
                    @click="openAddCateDialog('modify',data.cat_id,true)">
                    编辑
                  </el-button>
                  <el-button
                    type="text"
                    size="mini"
                    @click="deleteCate(data.cat_id,'tree',node,data)">
                    删除
                  </el-button>
                </span>
              </span>
            </el-tree>
          </template>
        </el-table-column>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column prop="cat_name" label="分类名称"></el-table-column>
        <el-table-column prop="cat_deleted" label="是否有效">
          <template slot-scope="scope">
            <i :class="!scope.row.cat_cat_deleted ? 'el-icon-success' : 'el-icon-error'"></i>
          </template>
        </el-table-column>
        <el-table-column prop="cat_level" label="排序">
          <template slot-scope="scope">
            <el-tag :type="scope.row.cat_level === 0 ? 'primary' : scope.row.cat_level === 1 ? 'success' : 'warning'">
              {{scope.row.cat_level === 0 ? '一级' : scope.row.cat_level === 1 ? '二级' : '三级'}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="">
            <el-button type="primary" class="el-icon-edit" size="mini"
                       @click="openAddCateDialog('modify',scope.row.cat_id)">编辑
            </el-button>
            <el-button type="danger" class="el-icon-delete" size="mini" @click="deleteCate(scope.row.cat_id)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="(pageSize) => {
          queryInfo.pagesize = pageSize
          getCateList()
        }"
        @current-change="(pageNum) => {
          queryInfo.pagenum = pageNum
          getCateList()
        }"
        :current-page="currentPage"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="5"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>

    <!--添加分类弹窗-->
    <el-dialog
      :title="isAdd ? '添加分类' : '修改分类信息'"
      :visible.sync="addCateDialogVisible"
      @close="handlerAddCateDialogClosed"
      :close-on-click-modal="false"
      width="50%"
    >
      <el-form :model="cateForm" ref="cateFormRef" label-width="100px" :rules="formRules">
        <el-form-item label="分类名称：" prop="cat_name">
          <el-input
            v-model="cateForm.cat_name"
            placeholder="输入分类名称"
          ></el-input>
        </el-form-item>
        <el-form-item v-if="isAdd" label="父级分类：">
          <el-cascader
            v-model="selectedOptionValue"
            :options="cateOptions"
            @change="handlerCascaderChange"
            :props="cateOptionProps"
            clearable
            expand-trigger="hover"
          >
          </el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="addCateDialogVisible = false">取 消</el-button>
    <el-button v-if="isAdd" type="primary" @click="addCate">确 定</el-button>
    <el-button v-else type="primary" @click="modifyCate">确认修改</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
import Breadcrumb from '@/components/Breadcrumb'
import { addCate, deleteCate, getCateInfoById, getCateList, modifyCateInfo } from '@/api/goods/cate'

export default {
  name: 'Cate',
  components: { Breadcrumb },
  data: () => {
    return {
      // 查询条件
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      // 分类数据
      cateList: [],
      total: 0,
      currentPage: 0,
      defaultProps: {
        label: 'cat_name',
        children: 'children'
      },
      addCateDialogVisible: false,
      cateForm: {
        cat_id: 0,
        cat_name: ''
      },
      cateOptions: [],
      selectedOptionValue: [],
      cateOptionProps: {
        checkStrictly: true,
        value: 'cat_id',
        label: 'cat_name'
      },
      selectedPid: 0,
      selectedLevel: 0,
      formRules: {
        cat_name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }]
      },
      isAdd: true,
      isModifyTree: false,
    }
  },
  created () {
    this.getCateList()
  },

  methods: {
    // 删除分类
    async deleteCate (cateId, type, node, data) {
      const r = await this.$confirm('确定要删除该分类？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (r !== 'confirm') {
        return this.$message.info('已取消删除！')
      }
      const { data: res } = await deleteCate(cateId)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      if (type === 'tree') {
        const parent = node.parent
        const children = parent.data.children || parent.data
        const index = children.findIndex(d => d.cat_id === data.id)
        children.splice(index, 1)
        return
      }
      await this.getCateList()
    },

    // 添加分类弹窗关闭
    handlerAddCateDialogClosed () {
      this.$refs.cateFormRef.resetFields()
      this.selectedOptionValue = []
      this.selectedPid = 0
      this.isModifyTree = false
    },

    // 修改分类
    async modifyCate () {
      const { data: res } = await modifyCateInfo(this.cateForm.cat_id, this.cateForm.cat_name)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      await this.getCateList()
      this.addCateDialogVisible = false
    },

    // 添加分类
    addCate () {
      this.$refs.cateFormRef.validate(async valid => {
        if (valid) {
          const cate = {
            cat_name: this.cateForm.cat_name,
            cat_pid: this.selectedPid,
            cat_level: this.selectedLevel
          }
          const { data: res } = await addCate(cate)
          if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
          this.$message.success(res.meta.msg)
          this.addCateDialogVisible = false
          await this.getCateList()
        }
      })
    },

    // 级联选择器变化
    handlerCascaderChange () {
      if (this.selectedOptionValue.length === 0) {
        this.selectedPid = 0
        this.selectedLevel = 0
        return
      }
      if (this.selectedOptionValue.length === 1) {
        this.selectedLevel = 1
      } else {
        this.selectedLevel = 2
      }
      this.selectedPid = this.selectedOptionValue[this.selectedOptionValue.length - 1]
    },

    // 打开添加分类弹窗
    async openAddCateDialog (type, cateId, isModifyTree) {
      const { data: res } = await getCateList({ type: 2 })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.cateOptions = res.data
      if (type === 'add') {
        this.isAdd = true
        this.cateForm.cat_name = ''
        this.addCateDialogVisible = true
      } else {
        this.isAdd = false
        const { data: res } = await getCateInfoById(cateId)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.cateForm.cat_id = res.data.cat_id
        this.cateForm.cat_name = res.data.cat_name
        if (isModifyTree) this.isModifyTree = isModifyTree
        this.addCateDialogVisible = true
      }
    },

    // 获取分类数据
    async getCateList () {
      const { data: res } = await getCateList(this.queryInfo)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.cateList = res.data.result
      this.total = res.data.total
      this.currentPage = res.data.pagenum + 1
    }
  }
}
</script>
<style lang="less" scoped>
  @import "./index";
</style>
